package com.eppear.jpfm.framework.websocket.server;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import com.eppear.jpfm.framework.websocket.WebSocketServerService;


/**
 * @ClassName HandshakeInterceptor
 * @Description websocket接连拦截器，主要用于校验握手参数是否正确。
 * @author JianFeng Zhang(张建锋)
 * @date 2017-09-26 上午8:35:12
 *
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

	private Logger log = LoggerFactory.getLogger(HandshakeInterceptor.class);

	@Autowired
	WebSocketServerService webSocketServerServic;  
	
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {

		super.beforeHandshake(request, response, wsHandler, attributes);
		log.debug("服务端 <============= 收到客户端连接请求");
		Boolean passFlag = false;
		// 获取连接握手时的参数,并进行校验,属性合法的才返回true,其它的返回false
		//String id = ((ServletServerHttpRequest) request).getServletRequest().getParameter("id");
		/*if (id != null && !"".equals(id)) {
			passFlag = true;
			attributes.put(WsConstants.WXID, Integer.valueOf(id));
		}*/
		
		Map<String, String> parmMap = this
				.transToMAP(((ServletServerHttpRequest) request).getServletRequest().getParameterMap());
		/*Integer id = Integer.valueOf(parmMap.get("id"));
		if(Server.isExist(id) && webSocketServerServic.checkSignature(parmMap)){*/
			
		if(webSocketServerServic.checkSignature(parmMap)){
			attributes.putAll(parmMap);
			passFlag = true;
		}else{
			log.info("服务端 <============= 收到客户端非法连接请求,握手参数为:[{}]",parmMap);
		}

		return passFlag;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {
		super.afterHandshake(request, response, wsHandler, ex);
		log.debug("服务端 ==============> 和客户端连接建立完成");
	}

	private Map<String, String> transToMAP(Map<String, String[]> parameterMap) {
		// 返回值Map
		Map<String, String> returnMap = new HashMap<String, String>();
		Iterator entries = parameterMap.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if (null == valueObj) {
				value = "";
			} else if (valueObj instanceof String[]) {
				String[] values = (String[]) valueObj;
				for (int i = 0; i < values.length; i++) {
					value = values[i] + ",";
				}
				value = value.substring(0, value.length() - 1);
			} else {
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}
}
